'use client'

import { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'
import { Sheet, Cell } from '@/types/sheet'
import { UnifiedSpreadsheetEditor } from '@/components/sheet/UnifiedSpreadsheetEditor'
import { ImportExportToolbar } from '@/components/sheet/ImportExportToolbar'
import { AuthModal } from '@/components/auth/AuthModal'
import { useAuth } from '@/contexts/AuthContext'
import { Wifi, WifiOff, Users, Lock, Edit } from 'lucide-react'

interface SharedSheetData {
  sheet: Sheet
  cells: Cell[]
}

export default function SharedSheetPage() {
  const params = useParams()
  const { user, loading: authLoading } = useAuth()
  const [sheetData, setSheetData] = useState<SharedSheetData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showAuthModal, setShowAuthModal] = useState(false)

  const shareToken = params.token as string

  // 获取分享的表格数据
  useEffect(() => {
    const fetchSharedSheet = async () => {
      try {
        setLoading(true)
        const response = await fetch(`/api/shared/${shareToken}`)
        
        if (!response.ok) {
          const errorData = await response.json()
          throw new Error(errorData.error || 'Failed to fetch shared sheet')
        }
        
        const data = await response.json()
        setSheetData(data)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error')
      } finally {
        setLoading(false)
      }
    }

    if (shareToken) {
      fetchSharedSheet()
    }
  }, [shareToken])

  // 处理单元格更新
  const handleCellUpdate = (row: number, column: number, value: string, formula?: string) => {
    if (!sheetData?.sheet.allowEdit) {
      alert('此表格不允许编辑')
      return
    }
    
    if (!user) {
      setShowAuthModal(true)
      return
    }
    
    console.log('Cell updated:', { row, column, value, formula })
  }

  // 处理样式更新
  const handleStyleUpdate = (row: number, column: number, style: any) => {
    if (!sheetData?.sheet.allowEdit) {
      alert('此表格不允许编辑')
      return
    }
    
    if (!user) {
      setShowAuthModal(true)
      return
    }
    
    console.log('Style updated:', { row, column, style })
  }

  // 处理保存
  const handleSave = (cells: Cell[]) => {
    if (!sheetData?.sheet.allowEdit) {
      alert('此表格不允许编辑')
      return
    }
    
    if (!user) {
      setShowAuthModal(true)
      return
    }
    
    console.log('Save cells:', cells)
  }

  // 处理分享
  const handleShare = () => {
    if (navigator.share) {
      navigator.share({
        title: sheetData?.sheet.title || '分享的表格',
        url: window.location.href
      })
    } else {
      navigator.clipboard.writeText(window.location.href)
      alert('分享链接已复制到剪贴板')
    }
  }

  // 处理导出
  const handleExport = (format: 'csv' | 'excel') => {
    console.log(`导出为${format}格式`)
  }

  // 处理导入
  const handleImport = async (importedCells: Cell[]) => {
    if (!sheetData?.sheet.allowEdit) {
      alert('此表格不允许编辑')
      return
    }
    
    if (!user) {
      setShowAuthModal(true)
      return
    }
    
    try {
      const token = localStorage.getItem('auth_token')
      const response = await fetch(`/api/sheets/${sheetData.sheet.id}/cells/batch`, {
        method: 'PUT',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ cells: importedCells })
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(`Failed to import cells: ${errorData.error || 'Unknown error'}`)
      }
      
      // 更新本地cells状态
      setSheetData(prev => prev ? { ...prev, cells: importedCells } : null)
      
      console.log('文件导入成功，共导入', importedCells.length, '个单元格')
      alert('文件导入成功')
    } catch (err) {
      console.error('Error importing cells:', err)
      alert('文件导入失败')
    }
  }

  if (authLoading || loading) {
    return null
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-red-600 mb-4">访问失败</h1>
          <p className="text-gray-600 mb-4">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            重新加载
          </button>
        </div>
      </div>
    )
  }

  if (!sheetData) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-600 mb-4">表格不存在</h1>
          <p className="text-gray-500">分享链接可能已失效</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* 头部信息 */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
        <div className="px-6 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
                {sheetData.sheet.title}
              </h1>
              {sheetData.sheet.description && (
                <p className="text-gray-600 dark:text-gray-400 mt-1">
                  {sheetData.sheet.description}
                </p>
              )}
              <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
                <span>由 {sheetData.sheet.owner.name} 分享</span>
                <div className="flex items-center gap-1">
                  {sheetData.sheet.allowEdit ? (
                    <>
                      <Edit size={14} />
                      <span>可编辑</span>
                    </>
                  ) : (
                    <>
                      <Lock size={14} />
                      <span>只读</span>
                    </>
                  )}
                </div>
              </div>
            </div>
            
            {/* 操作按钮 */}
            <div className="flex items-center gap-4">
              {/* 导入导出工具栏 */}
              <ImportExportToolbar
                sheet={sheetData.sheet}
                cells={sheetData.cells}
                onImport={handleImport}
                onExport={handleExport}
              />
              
              <button
                onClick={handleShare}
                className="px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                分享
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 工具栏已移除，使用 Univer 原生工具栏 */}

      {/* 表格 */}
      <div className="flex-1">
        <UnifiedSpreadsheetEditor
          sheet={sheetData.sheet}
          cells={sheetData.cells}
          onCellUpdate={handleCellUpdate}
          onStyleUpdate={handleStyleUpdate}
          onSave={handleSave}
          containerId="shared-univer-container"
          showCollaboration={true}
          allowEdit={sheetData.sheet.allowEdit}
        />
      </div>

      {/* 认证模态框 */}
      {showAuthModal && (
        <AuthModal
          isOpen={showAuthModal}
          onClose={() => setShowAuthModal(false)}
        />
      )}
    </div>
  )
}
